package com.junt.library.view;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.junt.library.R;
import com.junt.library.adapter.AudioAdapter;
import com.junt.library.adapter.MediaAdapter;
import com.junt.library.core.QueryType;
import com.junt.library.model.Media;
import com.junt.library.utils.GridMarginDecoration;

import java.util.List;

/**
 * Album page
 */
public class GridFragment extends Fragment {

    private static final String ARG_TYPE = "type";

    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;

    private QueryType queryType;

    public GridFragment() {
    }

    public static GridFragment newInstance(int queryType) {
        GridFragment gridFragment = new GridFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ARG_TYPE, queryType);
        gridFragment.setArguments(bundle);
        return gridFragment;
    }

    public void setNewData(List<Media> medias) {
        if (queryType == QueryType.AUDIO) {
            ((AudioAdapter) adapter).setNewData(medias);
        } else {
            ((MediaAdapter) adapter).setNewData(medias);
        }
    }

    public List<Media> getSelectedMedias(){
        if (adapter instanceof AudioAdapter){
            return ((AudioAdapter) adapter).getSelectedMedias();
        }
        return ((MediaAdapter) adapter).getSelectedMedias();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            queryType = QueryType.values()[getArguments().getInt(ARG_TYPE)];
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_grid, container, false);
        initRecyclerView(view);
        return view;
    }

    private void initRecyclerView(View view) {
        recyclerView = view.findViewById(R.id.recyclerView);
        GridMarginDecoration.set(recyclerView, 5);
        if (queryType == QueryType.AUDIO) {
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            adapter = new AudioAdapter(getContext());
        } else {
            recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 4));
            adapter = new MediaAdapter(getContext());
        }
        recyclerView.setAdapter(adapter);
    }

}